<script setup>
import {ref} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessageBox} from 'element-plus';
import {getDepartmentTreeApi, getUserListApi} from "@/service/user.js";
import { Plus,EditPen,Delete } from '@element-plus/icons-vue';
// 引入分页组件
import CommonPagination from '@/components/pagination.vue';

// 引入添加部门组件
import DepartmentAdd from './components/department-add.vue';
// 引入编辑部门组件
import DepartmentEdit from './components/department-edit.vue';

// 引入添加用户组件
import UserAdd from './components/user-add.vue';
// 引入编辑用户组件
import UserEdit from './components/user-edit.vue';

const router = useRouter();
// 过滤条件
const filterForm = ref({
  keyword: '',
  status: '',
  role_id: '',
  department_id: ''
});

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 15,
  total: 0
});

// 获取用户列表
const tableData = ref([]);
const fetchUserList = () => {
  let params = {
    ...filterForm.value,
    pagination
  }
  getUserListApi(params).then(res => {
    tableData.value = res.data.list;
    pagination.total = res.data.pagination.total;
  });
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchUserList();
};

// 重置
const handleReset = () => {
  filterForm.value = {
    keyword: '',
    status: '',
    role_id: '',
    department_id: ''
  };
  handleSearch();
};


// 添加用户
const UserAddRef = ref(null);
const showAddUserDialog = () => {
  UserAddRef.value.openDrawer();
};

// 编辑用户
const UserEditRef = ref(null);
const handleUserEdit = (row) => {
  UserEditRef.value.openDrawer(row);
};

const UserGrantRef = ref(null);
const handleUserGrand = (row) => {
  // router.push(`/user/grand/${row.name}`);
  let id = row.id;
  UserGrantRef.value.openDrawer(id);
};

const handleUserDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除用户 ${row.name} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    tableData.value = tableData.value.filter(item => item.name !== row.name);
  }).catch(() => {
  });
};

// ######################################### 部门相关 #########################################

// 获取部门树
const treeData = ref([]);
const fetchDepartmentTree = () => {
  getDepartmentTreeApi().then(res => {
    treeData.value = res.data.tree;
  });
};

// 切换部门节点的展开状态
const currentNode = ref({
  id: '',
  label: ''
});
const toggleNodeVisible = (node) => {
  console.log(node);
  currentNode.value = node;
};

// 鼠标移出树节点时，清空当前节点
const leaveTree = () => {
  // 添加延时，防止鼠标移出时，当前节点被清空
  setTimeout(() => {
    currentNode.value = {
      id: '',
      label: ''
    };
  }, 100);
};

// 显示添加部门弹窗
const DptRef = ref(null);
const showAddDepartmentDialog = (parentDpt) => {
  DptRef.value.openDialog(parentDpt);
};

// 显示编辑部门弹窗
const DptEditRef = ref(null);
const showEditDepartmentDialog = (department) => {
  DptEditRef.value.openDialog(department);
};

// 按照部门筛选用户
const filterUserByDpt = (id) => {
  filterForm.value.department_id = id;
  handleSearch();
};


// ######################################### 用户授权 #########################################
import UserGrant from "./components/user-grant.vue";

// 初始化数据
onMounted(() => {
  // 获取部门树
  fetchDepartmentTree();
  // 获取用户列表
  fetchUserList();
});
</script>

<template>
  <el-main>
    <div class="flex-main">
      <div class="flex-left">
        <el-tree
            :data="treeData"
            node-key="id"
            :expand-on-click-node="false"
            default-expand-all
            @mouseleave="leaveTree"
        >
          <template v-slot="{ node, data }">
            <div class="custom-tree-node" @click="toggleNodeVisible(node)">
              <div class="title" @click.stop="filterUserByDpt(node.id)">{{ node.label }}</div>
              <transition name="fade">
                <div class="right" v-if="node.id == currentNode.id">
                  <el-button :icon="Plus" type="primary" circle @click="showAddDepartmentDialog(data)" />
                  <el-button :icon="EditPen" type="primary" circle @click="showEditDepartmentDialog(node.parent, data)"/>
                  <el-button :icon="Delete" type="danger"  circle />
                </div>
              </transition>
            </div>
          </template>
        </el-tree>
      </div>
      <div class="flex-right">
        <div class="toolbar">
          <el-button type="primary" @click="showAddUserDialog">添加用户</el-button>
          <el-select v-model="filterForm.role_id" placeholder="用户角色">
            <el-option label="管理员" value="1"></el-option>
            <el-option label="普通用户" value="2"></el-option>
          </el-select>
          <el-select v-model="filterForm.status" placeholder="在职状态">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
          <el-input v-model="filterForm.keyword" placeholder="请输入关键字"></el-input>
          <el-button type="primary" @click="handleSearch" icon="Search">搜索</el-button>
          <el-button type="warning" @click="handleReset">重置</el-button>
        </div>
        <el-table class="list" :data="tableData" border style="width: 100%">
          <el-table-column prop="id" label="编号" align="center" width="55"></el-table-column>
          <el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
          <el-table-column prop="realname" label="姓名" width="120"></el-table-column>
          <el-table-column prop="role" label="角色" width="120">
            <template #default="{ row }">
              <el-tag v-for="item in row.role" :key="item.id" type="success" style="margin-right: 3px;">{{ item.title }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="管理性质" width="120" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.user_type == 1" type="success">普通用户</el-tag>
              <el-tag v-else-if="row.user_type == 2" type="primary">管理员</el-tag>
              <el-tag v-else type="info">外部用户</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="在职状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.status == 0" type="warning">已离职</el-tag>
              <el-tag v-else-if="row.status == 1" type="primary">在职</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" width="120"></el-table-column>
          <el-table-column prop="create_time" label="创建时间"></el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="primary" @click="handleUserEdit(row)">编辑</el-button>
              <el-button type="warning" @click="handleUserGrand(row)">授权</el-button>
              <el-button type="danger" @click="handleUserDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <CommonPagination :pagination="pagination" @pagination="fetchUserList"/>
        </div>
      </div>
    </div>

    <DepartmentAdd ref="DptRef" @reload="fetchDepartmentTree"/>
    <DepartmentEdit ref="DptEditRef" @reload="fetchDepartmentTree"/>

    <UserAdd ref="UserAddRef" @reload="fetchUserList" />
    <UserEdit ref="UserEditRef" @reload="fetchUserList" />
    <UserGrant ref="UserGrantRef" @reload="fetchUserList"/>
  </el-main>
</template>

<style scoped lang="less">
.flex-main {
  display: flex;
  flex-direction: row;
  width: 100%;
  overflow: hidden;

  .flex-left {
    flex: 0 20%;
  }

  .flex-right {
    flex: 1;
    padding-left: 10px;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
